<?php
/**
 * Created by PhpStorm.
 * User: zlkmu
 * Date: 2018/1/28
 * Time: 16:15
 */
namespace Protocols;
require_once "ProtocolAPI.php";
class GameProtocol{
    //TOTAL_LENGTH(4B) + HEAD_CODE(4B) + status(4B) + GAME_TYPE(2B) + USER_UID(4B)+AUDIO_LENGTH(4B) + CONTENT
    //发包的整体长度
    const PROTOCOL_PACK_LENGTH = 4;
    //实际信息的前缀包体长度
    const PROTOCOL_PREV_LENGTH = 22;
    public static function input($recv_buffer){
        //先获取实际长度
        if(strlen($recv_buffer) < self::PROTOCOL_PACK_LENGTH){
            return 0;
        }
        $unpack_data = unpack('Ntotal_length', $recv_buffer);
        return $unpack_data['total_length'];
    }

    public static function decode($recv_buffer){
        //解析前18个字节
        $recv_data = unpack('Ntotal_length/Nhead_request/Nstatus/ngame_type/Nuser_uid/Naudio_length', $recv_buffer);
        //解码实际的信息(判断是否是语音回调)
        if($recv_data["head_request"]==\ProtocolAPI::$SEND_AUDIO_REQUEST){
            //如果是语音不进行json_decode
            $recv_data['client_msg'] = substr($recv_buffer, self::PROTOCOL_PREV_LENGTH);
        }else{
            $recv_data['client_msg'] = json_decode(substr($recv_buffer, self::PROTOCOL_PREV_LENGTH), true);
        }
        return $recv_data;
    }

    public static function encode($data){
        $headCode = $data['head_code'];
        $status = $data['status'];
        $game_type = $data['game_type'];
        //返回数据是否存在user_uid，只是在消息回调中用,因为它有二进制流
        if(empty($data["user_uid"])){
            $user_uid = 0;
        }else{
            $user_uid = $data['user_uid'];
        }

        if(empty($data["audio_length"])){
            $audio_length=0;
        }else{
            $audio_length=$data["audio_length"];
        }

        if($headCode==\ProtocolAPI::$SEND_AUDIO_RESPONSE){
            $body_json_str = $data['client_msg'];
        }else{
            $body_json_str = json_encode($data['client_msg'],true);
        }
        $total_length = self::PROTOCOL_PREV_LENGTH + strlen($body_json_str);

        return pack('N', $total_length).pack('N', $headCode).pack('N', $status).pack('n', $game_type).pack('N', $user_uid).pack('N',$audio_length).$body_json_str;
    }
}


?>